import { FastifyReply } from 'fastify';
import { Body, Controller, Get, Post, Res } from '@nestjs/common';
import { TransformInterceptor } from '@/interceptor/transform.interceptor';
import { Public } from '@/utils/metadata/public';
import { AuthService } from './auth.service';
import { SignInDto } from './dto/sign-in.dto';

@Public()
@Controller('auth')
export class AuthController {
    constructor(private readonly authService: AuthService) {}

    @Post('login')
    async login(@Body() signInDto: SignInDto, @Res({ passthrough: true }) res: FastifyReply) {
        const { accessToken, userId, username } = await this.authService.signIn(signInDto.username, signInDto.password);
        const cookiesRes = { Authorization: 'Bearer ' + accessToken, userId, username };
        Object.entries(cookiesRes).forEach(([key, value]) => res.cookie(key, value, { path: '/' }));
        return { accessToken, userId, username, tokenType: 'Bearer' };
    }

    @Post('logout')
    async logout(@Res() res: FastifyReply) {
        res.clearCookie('Authorization')
            .clearCookie('userId')
            .clearCookie('username')
            .send(TransformInterceptor.success({}));
    }

    @Get('ping')
    ping() {
        return { pong: true };
    }
}
